package cn.sdut.training.cfg;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLDecoder;
import java.util.Properties;

public class Configuration {

	private static boolean installed; // 是否已安装的标记
	private static int pageSize; // 每页显示多少条记录

	private static String path; // default.properties的路径
	private static Properties props; // 配置

	/**
	 * 加载配置文件：default.properties，初始化配置
	 */
	static {
		try {

			// 1, 获取配置文件路径
			URL url = Configuration.class.getClassLoader().getResource("default.properties");
			path = URLDecoder.decode(url.getPath(), "utf-8");
			System.out.println(path);
			
			// 2，加载配置文件，并初始化配置
			props = new Properties();
			reload();

		} catch (Exception e) {
			System.out.println("0-------");
			throw new RuntimeException(e);
		}
	}

	/**
	 * 重新加载配置文件
	 */
	public static void reload() {
		InputStream in = null;
		try {

			// 1，加载配置文件
			in = new FileInputStream(path);
			props.load(in);

			// 2，初始化配置
			installed = "true".equals(props.getProperty("installed"));
			pageSize = Integer.parseInt(props.getProperty("pageSize"));

		} catch (Exception e) {
			throw new RuntimeException(e);
		} finally {
			try {
				in.close();
			} catch (IOException e) {
				throw new RuntimeException(e);
			}
		}
	}

	/**
	 * 保存配置到配置文件：default.properties
	 */
	public static void store() {
		FileOutputStream out = null;
		try {

			// 1，更新配置Properties
			props.setProperty("installed", String.valueOf(installed));
			props.setProperty("pageSize", String.valueOf(pageSize));

			// 2，保存到文件
			out = new FileOutputStream(path);
			props.store(out, "Update By Configuration");

		} catch (Exception e) {
			throw new RuntimeException(e);
		} finally {
			try {
				out.close();
			} catch (IOException e) {
				throw new RuntimeException(e);
			}
		}
	}

	// ===============

	public static boolean isInstalled() {
		return installed;
	}

	public static void setInstalled(boolean installed) {
		Configuration.installed = installed;
	}

	public static int getPageSize() {
		return pageSize;
	}

	public static void setPageSize(int pageSize) {
		Configuration.pageSize = pageSize;
	}

}
